package com.xc.pay.weixin.util;

import cn.hutool.core.util.ReUtil;
import com.xc.pay.common.MessageTemplate;
import jodd.util.ResourcesUtil;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;

public class CertUtil {

  private final Logger log = LoggerFactory.getLogger(this.getClass());

  /** 加载证书 */
  public static SSLConnectionSocketFactory initCert(String mch_id, String certUrl)
      throws Exception {
    FileInputStream instream = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    File file = new File(certUrl);
    instream = new FileInputStream(file);
    keyStore.load(instream, mch_id.toCharArray());
    if (null != instream) {
      instream.close();
    }
    SSLContext sslcontext =
        SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(
            sslcontext,
            new String[] {"TLSv1"},
            null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return sslsf;
  }

  /**
   * 从配置路径 加载配置 信息（支持 classpath、本地路径、网络url）
   *
   * @param configPath 证书路径
   */
  public static InputStream loadConfigInputStream(String configPath) {
    InputStream inputStream = null;
    final String prefix = "classpath:";
    String fileNotFoundMsg = String.format(MessageTemplate.NOT_FOUND_MSG, configPath);
    if (configPath.startsWith(prefix)) {
      String path = ReUtil.delFirst(configPath, prefix);
      if (!path.startsWith("/")) {
        path = "/" + path;
      }
      try {
        inputStream = ResourcesUtil.getResourceAsStream(path);
        if (inputStream == null) {
          throw new FileNotFoundException(fileNotFoundMsg);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (configPath.startsWith("http://") || configPath.startsWith("https://")) {
      try {
        inputStream = new URL(configPath).openStream();
        if (inputStream == null) {
          throw new FileNotFoundException(fileNotFoundMsg);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      try {
        File file = new File(configPath);
        if (!file.exists()) {
          throw new FileNotFoundException(fileNotFoundMsg);
        }
        inputStream = new FileInputStream(file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return inputStream;
  }
}
